package com.itany.shop.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author 石小俊
 */
@WebListener
public class CountUserListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSessionListener.super.sessionCreated(se);
        // application属于ServletContext类型
        // 该对象有两种使用场景
        // 1.在Servlet中,可以直接调用GenericServlet中的提供的方法,仅限Servlet中使用
        // ServletContext application = super.getServletContext();
        // 2.通用型,可以根据request或者session直接调用
        // request.getServletContext()
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        synchronized (this) {
            Integer count = (Integer) application.getAttribute("count");
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            application.setAttribute("count", count);
        }
    }
}
